const fetch = require("node-fetch");
const url = require("url");
const querystring = require("querystring");
const {
  redis_client,
  redis_prefix,
  md5,
  db,
  dbPromise,
  fbadmin
} = require("../unit");
const { User } = require("./admin");

exports.setup = router => {
  router.get("/wx-code-cb", async (ctx, next) => {
    const { code, redirect_uri, share_code } = ctx.query;
    if (!code) {
      throw "参数错误";
    }
    const user_info = await fetch(
      `http://wx.youdob.org/get_user_info.php?code=${code}&pwd=${encodeURIComponent("XaruQnDp--Gaubee--D8rKFC84")}`
    ).then(res => res.json());
    if (!user_info.openid) {
      throw JSON.stringify(user_info);
    }
    const user = new User(user_info);
    const user_kid = user.id;
    // 异步保存用户信息到firebase 服务器
    console.log("同步保存用户信息到firebase服务器");
    const userRef = db.ref("users/" + user_kid);
    const val = await dbPromise(userRef, {
      can_null: true
    });
    if (val) {
      console.log("更新用户信息");
      userRef
        .update(
          Object.assign(
            {
              last_login_time: Date.now()
            },
            user_info
          )
        )
        .then(res => {
          console.log("用户数据修改成功");
        })
        .catch(err => {
          console.error("用户数据修改失败", err);
        });
    } else {
      let from_share_user;
      if (share_code) {
        console.log("有分享码，监测分享码");
        const share_user = await dbPromise(db.ref("users/" + share_code), {
          can_null: true
        });
        if (share_user) {
          // 用户存在，给用户加水豆
          console.log(
            `分享码有效，用户${share_user.nickname}返还水豆奖励:${User.setting.share_return_points}`
          );
          from_share_user = share_code;
          User.addPoints(share_code, User.setting.share_return_points);
        }
      }
      console.log("创建新的用户");
      const base_user_info = {
        create_time: Date.now(),
        last_login_time: Date.now(),
        points: User.setting.init_points || 0,
        cards: User.setting.init_cards || 0
      };

      if (from_share_user) {
        base_user_info.from_share_user = from_share_user;
      }
      userRef
        .set(Object.assign(base_user_info, user_info))
        .then(res => {
          console.log("用户数据创建成功");
        })
        .catch(err => {
          console.error("用户数据创建失败", err);
        });
    }

    const user_session = Date.now() + Math.random().toString(36);

    await redis_client.writeStringAsync(
      redis_prefix + "session-user-id-" + user_session,
      user_kid
    );
    // 反向校验
    await redis_client.writeObjectAsync(
      redis_prefix + "user-id-session-info-" + user_kid,
      {
        user_session,
        // 有效期为24小时
        time_out: Date.now() + 24 * 60 * 60 * 1000,
        user_info: user
      }
    );

    ctx.body = user;
    if (redirect_uri) {
      const redirect_uri_info = url.parse(redirect_uri);
      const query_info = querystring.parse(redirect_uri_info.query);
      query_info.u = user_session;
      redirect_uri_info.search = "?" + querystring.stringify(query_info);
      const redirect_uri_with_uid = url.format(redirect_uri_info);
      ctx.set("Location", redirect_uri_with_uid);
      ctx.status = 302;
    }
  });
};
